'use strict';
const db = uniCloud.database();
exports.main = async (event, context) => {
	// 接收客户端上传的参数
	console.log('event : ', event)
	let params = { ...event };
	
	// 清理空值查询条件
	for (let key in params) {
		if (!params[key]) {
			delete params[key];
		} else if (key !== '_id' && key !== 'queryId') {
			// 非ID字段使用模糊查询
			params[key] = new RegExp(params[key], 'g');
		}
	}
	
	try {
		// 1. 查询所有符合条件的菜单分类，按创建时间正序排序
		const menuRes = await db.collection('menu')
			.where(db.command.or({ ...params }))
			.orderBy('createTime', 'asc') // 关键修改：将desc改为asc实现正序排序
			.get();
		
		const dataList = menuRes.data || [];
		const total = dataList.length;
		
		if (total === 0) {
			return {
				code: 200,
				message: "操作成功",
				data: [],
				total: 0
			};
		}
		
		// 2. 提取所有分类ID，一次性查询所有子菜单
		const classIds = dataList.map(item => item._id);
		
		const menuDetailRes = await db.collection('menuDetail')
			.where({ classId: db.command.in(classIds) })
			.orderBy('createTime', 'asc')
			.get();
		
		const allChildren = menuDetailRes.data || [];
		
		// 3. 在内存中进行分类匹配
		dataList.forEach(menu => {
			menu.children = allChildren.filter(child => child.classId === menu._id);
		});
		
		return {
			code: 200,
			message: "操作成功",
			data: dataList,
			total: total
		};
	} catch (error) {
		console.error('查询出错:', error);
		return {
			code: 500,
			message: "查询失败",
			error: error.message
		};
	}
};
    